/*
 * @lc app=leetcode.cn id=236 lang=typescript
 *
 * [236] 二叉树的最近公共祖先
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
//  思路：后续遍历递归
//  参考：https://mp.weixin.qq.com/s/9RKzBcr3I592spAsuMH45g

function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
    //  base case
    if (!root) return null
    if (root === p || root === q) return root

    const left = lowestCommonAncestor(root!.left, p, q)
    const right = lowestCommonAncestor(root!.right, p, q)

    // p、q都在以root为根的树中
    if (left && right) {
        return root
    }
    // p、q都不在
    if (!left && !right) {
        return null
    }
    return left ?? right
};
// @lc code=end

import { TreeNode } from './type'
const root = TreeNode.buildTree([3, 5, 1, 6, 2, 0, 8, null, null, 7, 4])
const p = root!.left
const q = root!.right
console.log(lowestCommonAncestor(root, p, q))
